// 团体测评
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="测评名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入测评名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="量表类型" prop="category">
        <el-cascader
          :options="scaleTypeList"
          v-model="queryParams.category"
          @change="muchChange"
          style="width: 240px"
          :props="{ checkStrictly: true }"
          clearable
          :show-all-levels="false"
          :disabled="displays"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="适应对象" prop="typex">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择适应对象"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.suitable_object"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="测试时长" prop="status">
        <el-input
          v-model="queryParams.duration"
          placeholder="请输入测试时长"
          clearable
          type="number"
          min="0"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>
      <el-form-item label="测评状态" prop="measureStatus">
        <el-select
          v-model="queryParams.measureStatus"
          placeholder="请选择测评状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.measure_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="测评日期">
        <!-- <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
                    type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker> -->
        <el-date-picker
          v-model="dateRange1"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        > -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
          >发起测评</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="测评名称" align="center" key="name" prop="name" />
      <el-table-column
        label="量表名称"
        align="center"
        key="formName"
        prop="formName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="量表类型"
        align="center"
        key="categoryDictText"
        prop="categoryDictText"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="测评范围"
        align="center"
        key="deptName"
        prop="dept.deptName"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        label="测试用时（分钟）"
        align="center"
        key="duration"
        prop="duration"
      />
      <el-table-column
        label="测评时段"
        align="center"
        prop="createTime"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.startDate }}</span>
          <span>—</span>
          <span>{{ scope.row.endDate }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="测评状态"
        align="center"
        key="measureStatusDictText"
        prop="measureStatusDictText"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="reportClik(scope.row)"
            v-hasPermi="['system:user:edit']"
            >报告</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="handleUpdate(scope.row, '详情')"
            v-hasPermi="['system:user:edit']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="enable(scope.row, '1')"
            v-hasPermi="['system:user:remove']"
            >启用</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="enable(scope.row, '2')"
            v-hasPermi="['system:user:remove']"
            >禁用</el-button
          >
        
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :span="24">
          <el-col :span="24">
            <el-form-item label="测评名称：" prop="name">
              <el-input v-model="form.name" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="采用量表" prop="formId">
              <el-select
                v-model="form.formId"
                clearable
                placeholder="请选择量表"
                @change="handleChange"
              >
                <el-option
                  v-for="item in scaleList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="量表类型:">
              <div>{{ objMatter.categoryDictText }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适应对象:">
              <div>{{ objMatter.typeDictText }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="测评时间段:" prop="startDate">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测试时长:" prop="duration">
              <el-input
                v-model="form.duration"
                placeholder="请输入测试时长"
                clearable
                type="number"
                min="0"
              >
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="测试人员:" prop="schoolIds">
              <el-select
                v-model="form.schoolIds"
                clearable
                placeholder="请选择学校"
                @change="shoolChange"
              >
                <el-option
                  v-for="item in schoolList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="form.classIds"
              multiple
              placeholder="请选择班级"
            >
              <el-option
                v-for="item in classList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">发 布</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateUser } from "@/api/system/user";
import {
  schoolPage, //获取学校
  classPull, //年级列表
} from "@/api/information/index";
import {
  formcfgList, //量表列表
  settingSaveOrUpdate, //发起测评
  formSetting, //测评详情
  formSettingDel, //删除测评
  typeTree, //量表类型
  settingChangeStatus, //修改测评状态
} from "@/api/itemBank/index";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: [
    "sys_normal_disable",
    "sys_user_sex",
    "suitable_object",
    "measure_status",
  ],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //禁止输入
      displays: false,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 学校选项
      schoolList: [],
      //  班级
      classList: [],
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 搜素日期范围
      dateRange1: [],
      // 量表选项
      scaleList: [],
      //量表类型
      scaleTypeList: [],
      // 角色选项
      roleOptions: [],
      objMatter: {},
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,

        status: undefined,
        deptId: undefined,
      },

      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入测评名称", trigger: "blur" }],
        formId: [{ required: true, message: "请选择量表", trigger: "blur" }],
        // startDate: [
        //   { required: true, message: "请选择开始时间", trigger: "blur" },
        // ],
        schoolIds: [
          { required: true, message: "请选择测评人员", trigger: "blur" },
        ],
        duration: [
          {
            required: true,
            message: "请输入测评时长",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {},
  created() {
    this.getList();
    this.getDeptTree();
    this.getNormalScale();
    this.getScaleType();
  },
  methods: {
    // 获取正常量表
    getNormalScale() {
      // usingStatus: 0 //启用状态
      formcfgList({ usingStatus: 0,examType:1}).then((response) => {
        this.scaleList = response.rows;
      });
    },
    // 获取所有量表类型
    getScaleType() {
      typeTree().then((response) => {
        this.scaleTypeList = JSON.parse(
          JSON.stringify(response.data).replace(/id/g, "value")
        );
      });
    },

    /** 查询学校下拉树结构 */
    getDeptTree() {
      schoolPage({ type: 2 }).then((res) => {
        this.schoolList = res.rows;
      });
    },
    /** 查询班级下拉树结构 */
    shoolChange(val) {
      if (val) {
        classPull(val).then((res) => {
          this.classList = res.data;
        });
      }
    },
    handleChange(val) {
      this.scaleList.forEach((item) => {
        if (item.id === val) {
          this.objMatter = item;
          console.log("KKK", item);
        }
      });
    },
    muchChange(value) {
      if (value) {
        this.queryParams.category = value[value.length - 1];
      }
    },
    /** 查询测评列表 */
    getList() {
      this.loading = true;
      this.queryParams.measureType = "1";
      formSetting(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateRange = [];
      this.objMatter = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      (this.queryParams.startDate = this.dateRange1[0]),
        (this.queryParams.endDate = this.dateRange1[1]),
        (this.queryParams.measureType = "1"); //团测
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.dateRange = [];
       this.dateRange1=[]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.open = true;
      this.title = "发起测评";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.reset();
      this.open = true;
      this.dateRange = [];
      if (type == "详情") {
        this.title = "测评详情";
        this.form = row;
        this.objMatter.typeDictText = this.form.typeDictText;
        this.objMatter.categoryDictText = this.form.categoryDictText;
        (this.dateRange[0] = this.form.startDate),
          (this.dateRange[1] = this.form.endDate),
          (this.form.schoolIds = row.schoolIds.toString());
        this.shoolChange(this.form.schoolIds);
        this.form.classIds = row.classIds.map((item) => item.toString());

        console.log("数组", this.form.classIds);
      } else {
        this.title = "发起测评";
      }
    },

    /** 提交按钮 */
    submitForm: function () {
      (this.form.startDate = this.dateRange[0]),
        (this.form.endDate = this.dateRange[1]),
        (this.form.measureType = "1"); //团测
      this.form.type = this.objMatter.type;
      this.form.category = this.objMatter.category;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            settingSaveOrUpdate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除测评编号为"' + userIds + '"的数据项？')
        .then(function () {
          return formSettingDel(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 启用
    enable(row, type) {
      let text = "";
      if (type == "1") {
        text = "启用";
      } else {
        text = "禁用";
      }
      this.$modal
        .confirm("确认" + text + "测评编号为" + row.id + '"的数据项？')
        .then(function () {
          return settingChangeStatus({ id: row.id, usingStatus: type });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(() => {});
    },

    //上传模型
    reportClik() {
      this.upload.title = "测评报告";
      this.upload.open = true;
    },

    // 提交上传文件
    submitFileForm() {},
  },
};
</script>